﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using CIT.WMS.houseWork.Helper;

namespace CIT.WMS.input
{
    public partial class WWInput : Form
    {
        bool flag = false;
        bool result = false;
        public WWInput()
        {
            InitializeComponent();
            databind();
        }

        private void databind()
        {
            string strSql = string.Format(@"SELECT PO,POID FROM dbo.T_Bllb_POMain_tbpm WHERE Status='0' AND PO_TypeCode='2' ORDER BY CreateTime DESC");//委外订单
            DataTable dt_po = Utils.NMS.QueryDataTable(Utils.uContext, strSql, new CIT.WMS.MESWcf.CmdParameter[0]);
            DataRow dr = dt_po.NewRow();
            dr["PO"] = string.Empty;
            dr["POID"] = string.Empty;
            dt_po.Rows.InsertAt(dr, 0);
            cbo_PO.DisplayMember = "PO";
            cbo_PO.ValueMember = "POID";
            cbo_PO.DataSource = dt_po;
         
        }

        private void txt_reelid_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                ClearControl();
                string POID = string.Empty;
                //供应商代码|料号|唯一码|数量|生产日期（datacode或批次）|订单号|行号
                string[] strs = txt_reelid.Text.Trim().Split('|');
                if (strs.Length != 7)
                {
                    DataTable dt_po = Utils.NMS.QueryDataTable(Utils.uContext, "select Status,POID from T_Bllb_POMain_tbpm where PO='" + txt_reelid.Text.Trim() + "' and PO_TypeCode='2'", new CIT.WMS.MESWcf.CmdParameter[0]);
                    if ( dt_po.Rows.Count== 0)//若是输入的不是委外订单，那么就认为是来料条码
                    {
                        lbl_msg.Text = "物料条码有误或委外订单不存在.";
                        lbl_msg.ForeColor = Color.Red;
                        txt_reelid.Text = string.Empty; ;
                        txt_reelid.Focus();
                        return;
                    }
                    else //判断委外订单是否正确
                    {
                        if (SqlInput.ChangeNullToString(dt_po.Rows[0][0]) == "2")
                        {
                            lbl_msg.Text = "来料所属委外订单已关闭.";
                            lbl_msg.ForeColor = Color.Red;
                        
                        }
                        else
                        {
                            cbo_PO.Text = txt_reelid.Text.Trim();
                            lbl_msg.Text = "委外订单设置成功.";
                            lbl_msg.ForeColor = Color.Green;
                        }
                        txt_reelid.Text = string.Empty; ;
                        txt_reelid.Focus();
                        return;
                    }
                 
                }
                else
                {
                    if (cbo_PO.Text== string.Empty)
                    {
                        lbl_msg.Text = "请选择委外订单";
                        lbl_msg.ForeColor = Color.Red;
                        txt_reelid.Text = string.Empty; ;
                        txt_reelid.Focus();
                        return;
                    }
                
                    //string[] strs = txt_reelid.Text.Trim().Split('|');
                    if (strs.Length == 7)
                    {
                        string po = strs[5].ToString();//采购订单号
                        if (po != cbo_PO.Text.Trim())
                        {
                            lbl_msg.Text = "物料不属于当前委外订单";
                            lbl_msg.ForeColor = Color.Red;
                            txt_reelid.Text = string.Empty; ;
                            txt_reelid.Focus();
                            return;
                        }
                        string lot_no = strs[2].ToString();//批次号（唯一码）
                        string poid = string.Empty;//采购订单ID
                        string doc_no = string.Empty;//清点单号
                        string rownumber = string.Empty;//行号
                        string MaterialCode = strs[1].ToString(); //料号
                        string PO_DetailID=string.Empty;
                        int qty=0;
                        qty = SqlInput.ChangeNullToInt(strs[3].ToString(), 0);//数量
                        string strSql = string.Empty;
                        rownumber = strs[6].ToString();//行号
                        strSql = string.Format(@"SELECT PO_DetailID,Quantity,ClearQty FROM dbo.T_Bllb_PODetail_tbpd WHERE POID='{0}' AND RowNumber='{1}' and MaterialCode='{2}'", poid, rownumber, MaterialCode);
                        DataTable dt_podetail = Utils.NMS.QueryDataTable(Utils.uContext, strSql, new CIT.WMS.MESWcf.CmdParameter[0]);
                        if(dt_podetail.Rows.Count==0)
                        {
                             lbl_msg.Text = "委外订单中不存在此物料.";
                            lbl_msg.ForeColor = Color.Red;
                            txt_reelid.Text = string.Empty; ;
                            txt_reelid.Focus();
                            return;
                        }
                                              

                        PO_DetailID = dt_podetail.Rows[0][0].ToString();//委外订单字表ID
                        strSql = string.Format(@"SELECT SerialNumber FROM T_Bllb_StorageDocDetail_tbsdd WHERE  SerialNumber='{0}' AND S_Doc_Type='4'", txt_reelid.Text.Trim());
                        DataTable dt_serial= Utils.NMS.QueryDataTable(Utils.uContext, strSql, new CIT.WMS.MESWcf.CmdParameter[0]);
                        if (dt_serial.Rows.Count > 0)
                        {
                            lbl_msg.Text = "此物料已入库";
                            lbl_msg.ForeColor = Color.Red;
                            txt_reelid.Text = string.Empty; ;
                            txt_reelid.Focus();
                            return;
                        }
                        //判断清点单是否已生成，若无则自动生成入库单
                        DataTable dt_doc = Utils.NMS.QueryDataTable(Utils.uContext, string.Format("SELECT  S_Doc_NO  FROM T_Bllb_StorageDoc_tbsd WHERE PO='{0}'and Create_Time>=CONVERT(CHAR(10),GETDATE(),120) AND S_Doc_Type='4'", cbo_PO.Text.Trim()), new CIT.WMS.MESWcf.CmdParameter[0]);
                        if (dt_doc.Rows.Count == 0)
                        {
                            dt_doc = Utils.NMS.QueryDataTable(Utils.uContext, string.Format("SELECT  RIGHT(S_Doc_NO,4)+1  FROM T_Bllb_StorageDoc_tbsd WHERE Create_Time>=CONVERT(CHAR(10),GETDATE(),120) AND S_Doc_Type='4'"), new CIT.WMS.MESWcf.CmdParameter[0]);
                            if (dt_doc.Rows.Count > 0)
                            {
                                doc_no = "WWR" + DateTime.Now.ToString("yyMMdd") +SqlInput.ChangeNullToInt(dt_doc.Rows[0][0],0).ToString("0000");
                            }
                            else
                            {
                                doc_no = "WWR" + DateTime.Now.ToString("yyMMdd") + "0001";
                            }
                           
                            strSql = string.Format(@"INSERT INTO dbo.T_Bllb_StorageDoc_tbsd
                                                    ( S_Doc_NO ,
                                                      S_Doc_Type ,
                                                      Create_Time ,
                                                      Creator ,
                                                      PO ,
                                                      POID
                                                    )
                                            VALUES  ( '{0}' , -- S_Doc_NO - nvarchar(50)
                                                      '1' , -- S_Doc_Type - nvarchar(10)
                                                      GETDATE() , -- Create_Time - datetime
                                                      '{1}' , -- Creator - nvarchar(50)
                                                      '{2}' , -- PO - nvarchar(50)
                                                      '{3}' -- POID - nvarchar(50)      
                                                    )", doc_no, Utils.uContext.UserIDk__BackingField , po, poid);  //供应商代码|料号|唯一码|数量|生产日期（datacode或批次）|订单号|行号
            
                            Utils.NMS.Exectransql(Utils.uContext, strSql, new CIT.WMS.MESWcf.CmdParameter[0], out flag, out result);

                       
                        }
                        else
                        {
                            doc_no = dt_doc.Rows[0][0].ToString();
                        }
                        int totalQty = 0;
                        strSql = string.Format(@"SELECT S_Doc_NO,QTY FROM T_Bllb_StorageDocMaterial_tsdm WHERE S_Doc_NO='{0}' AND RowNumber='{1}'", doc_no, rownumber);
                        //判断采购入库单中是否已存在某物料
                        DataTable dt_doc_material = Utils.NMS.QueryDataTable(Utils.uContext, strSql, new CIT.WMS.MESWcf.CmdParameter[0]);
                    
                        if (dt_doc_material.Rows.Count == 0)
                        {  
                            strSql = string.Format(@"INSERT INTO dbo.T_Bllb_StorageDocMaterial_tsdm
                                                    ( S_Doc_NO ,
                                                      MaterialCode ,
                                                      QTY ,
                                                      RowNumber ,
                                                      PO_DetailID 
                                                    )
                                            VALUES  ( '{0}' , -- S_Doc_NO - nvarchar(50)
                                                      '{1}' , -- MaterialCode - nvarchar(50)
                                                      {2} , -- QTY - int
                                                      {3} , -- RowNumber - int
                                                      '{4}'  -- PO_DetailID - nvarchar(50) 
                                                    )", doc_no, MaterialCode, qty, rownumber, PO_DetailID);
                  
                            Utils.NMS.Exectransql(Utils.uContext, strSql, new CIT.WMS.MESWcf.CmdParameter[0], out flag, out result);
                            totalQty = qty;
                        }
                        else
                        {
                          
                            strSql = string.Format(@"UPDATE T_Bllb_StorageDocMaterial_tsdm SET QTY=QTY+{2} WHERE S_Doc_NO='{0}' AND RowNumber={1}",doc_no,rownumber,qty);
                      
                            Utils.NMS.Exectransql(Utils.uContext, strSql, new CIT.WMS.MESWcf.CmdParameter[0], out flag, out result);

                            totalQty = SqlInput.ChangeNullToInt(dt_doc_material.Rows[0]["QTY"].ToString(), 0) + qty;
                        }

                        strSql = string.Format(@"INSERT INTO dbo.T_Bllb_StorageDocDetail_tbsdd
                                                ( S_Doc_NO ,
                                                  MaterialCode ,
                                                  QTY ,
                                                  Create_Time ,
                                                  Creator ,
                                                  SerialNumber ,  
                                                  RowNumber ,
                                                  PO_DetailID,Lot_No
                                                )
                                        VALUES  ( '{0}' , -- S_Doc_NO - nvarchar(50)
                                                  '{1}' , -- MaterialCode - nvarchar(50)
                                                  {2} , -- QTY - int
                                                  GETDATE() , -- Create_Time - datetime
                                                  '{3}' , -- Creator - nvarchar(50)
                                                  '{4}' , -- SerialNumber - nvarchar(50)   
                                                  {5} , -- RowNumber - int
                                                  '{6}',  -- PO_DetailID - nvarchar(50)
                                                   '{7}'
                                                )", doc_no, MaterialCode, qty, Utils.uContext.UserIDk__BackingField, txt_reelid.Text.Trim(), rownumber, PO_DetailID, lot_no);
                         Utils.NMS.Exectransql(Utils.uContext, strSql, new CIT.WMS.MESWcf.CmdParameter[0], out flag, out result);
                         lbl_TotalQty.Text = totalQty.ToString();
                         lbl_QTY.Text = qty.ToString();
                         lbl_PO.Text = po.ToString();
                         lbl_MaterialCode.Text = MaterialCode;
                         lbl_RowNumber.Text = rownumber;
                       

                        //委外入库数累计
                         strSql = string.Format(@" UPDATE T_Bllb_PODetail_tbpd SET ClearQty= ISNULL(CurrentReceiveQty,0)+{3}  WHERE POID='{0}' AND RowNumber='{1}' and MaterialCode='{2}'", poid, rownumber, MaterialCode, qty);
                        Utils.NMS.Exectransql(Utils.uContext, strSql, new CIT.WMS.MESWcf.CmdParameter[0], out flag, out result);
                    }
                    else
                    {
                        lbl_msg.Text = "物料条码不符合，无法解析";
                        lbl_msg.ForeColor = Color.Red;
                        txt_reelid.Text = string.Empty; ;
                        txt_reelid.Focus();
                        return;
                    }
                    lbl_msg.Text = "OK";
                    lbl_msg.ForeColor = Color.Green;
                    txt_reelid.Text = string.Empty; ;
                    txt_reelid.Focus();
                }
             
            }
        }

        private void cbo_PO_SelectedIndexChanged(object sender, EventArgs e)
        {
            ClearControl();
        }

        private void ClearControl()
        {
            lbl_MaterialCode.Text = string.Empty;//料号
            lbl_PO.Text = string.Empty;//委外订单
            lbl_QTY.Text = string.Empty;//当前物料数量
            lbl_TotalQty.Text = string.Empty;//入库总数
            lbl_msg.Text = string.Empty;//提示信息
            lbl_RowNumber.Text = string.Empty;//行号
        }

        private void cbo_PO_LostFocus(object sender, EventArgs e)
        {
            if (cbo_PO.Text.Trim() != string.Empty)
            {
                string strSql = string.Format(@"SELECT Status FROM T_Bllb_POMain_tbpm WHERE PO = '{0}' and PO_TypeCode='2'", cbo_PO.Text.Trim());
                DataTable dt_po = Utils.NMS.QueryDataTable(Utils.uContext, strSql, new CIT.WMS.MESWcf.CmdParameter[0]);
                if (dt_po.Rows.Count == 0)
                {
                    lbl_msg.Text = "委外订单不存在";
                    lbl_msg.ForeColor = Color.Red;
                    return;
                }
                else if (SqlInput.ChangeNullToString(dt_po.Rows[0][0]) == "2")
                {
                    lbl_msg.Text = "委外订单已关闭";
                    lbl_msg.ForeColor = Color.Red;
                    return;
                }
                lbl_msg.Text = "委外订单设置OK";
                lbl_msg.ForeColor = Color.Green;
                return;
            
            }
        }
    }
}